package com.tsingteng.cosfun.widget.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.App;
import com.tsingteng.cosfun.app.DialogListener;
import com.tsingteng.cosfun.bean.AttentFansbean;
import com.tsingteng.cosfun.bean.BaseBackBean;
import com.tsingteng.cosfun.bean.CommBean;
import com.tsingteng.cosfun.ui.cosfun.AtFragment;
import com.tsingteng.cosfun.ui.cosfun.contract.CommContract;
import com.tsingteng.cosfun.ui.cosfun.presenter.CommPresenter;
import com.tsingteng.cosfun.utils.DialogUtil;
import com.tsingteng.cosfun.utils.KeywordUtil;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CommentDialog extends DialogFragment implements TextWatcher, View.OnClickListener, CommContract.ICommView {

    //点击发表，内容不为空时的回调
    public CommentDialogListener commentDialogListener;

    EditText et;
    TextView at;
    TextView send;
    String workId = "";
    String commId = "";//回复评论id
    int isTop = 0;
    int position;//点击的评论下标
    CommPresenter commPresenter = null;
    List<AttentFansbean.Data> atList = null;
    AttentFansbean.Data data = null;
    private long mProfileId;
    private String mNickname;
    String contentMsg;
    DialogListener dialogListener;

    public CommentDialog() {
    }


    @SuppressLint("ValidFragment")
    public CommentDialog(int isTops,int position, String workId, String commId, AttentFansbean.Data data, CommentDialogListener commentDialogListener
            , DialogListener listener) {
        this.isTop = isTops;
        this.workId = workId;
        this.commId = commId;
        this.data = data;
        this.commentDialogListener = commentDialogListener;
        this.dialogListener = listener;
        this.position = position;
        atList = new ArrayList<>();
    }
    @SuppressLint("ValidFragment")
    public CommentDialog(int position, String workId, String commId, AttentFansbean.Data data, CommentDialogListener commentDialogListener
            , DialogListener listener) {
        this.workId = workId;
        this.commId = commId;
        this.data = data;
        this.commentDialogListener = commentDialogListener;
        this.dialogListener = listener;
        this.position = position;
        atList = new ArrayList<>();
    }


    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。
        Dialog dialog = new Dialog(Objects.requireNonNull(getActivity()), R.style.Comment_Dialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        View contentView = View.inflate(getActivity(), R.layout.bottom_input_dialog, null);
        dialog.setContentView(contentView);
        dialog.setCanceledOnTouchOutside(true); // 外部点击取消

        // 设置宽度为屏宽, 靠近屏幕底部。
        Window window = dialog.getWindow();
        assert window != null;
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.alpha = 1;
        lp.dimAmount = 0.0f;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
        window.setAttributes(lp);
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);


//        tv_send.setOnClickListener(this);

        et = contentView.findViewById(R.id.bottom_input_dialog_et);

        at = contentView.findViewById(R.id.bottom_input_dialog_at);
        send = contentView.findViewById(R.id.bottom_input_dialog_send);
        at.setOnClickListener(this);
        send.setOnClickListener(this);
        send.setClickable(true);
        commPresenter = new CommPresenter(this);
        et.addTextChangedListener(this);
        if (data != null) {
            atList.add(data);
            String s = et.getText().toString() + "@" + data.nickName;
            et.setText(s);
        }
        return dialog;
    }

    int l = 0;//记录字符串被删除字符之前，字符串的长度
    int location = 0;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        l = s.length();
        location = et.getSelectionStart();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        LogUtils.e("testcomm", "txt=" + s);

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (l != s.toString().length()) {
            String input = s.toString();
            SpannableString msp = KeywordUtil.matcherAtTxt(Color.parseColor("#42DAD7"), input, atList);
            et.setText(msp);
            et.setSelection(et.getText().toString().length());
        }
        if (s.toString().length() >= 200) {
            Toast.makeText(App.getContext(), "最多可以评论200个字呦", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bottom_input_dialog_send:
                if (TextUtils.isEmpty(et.getText().toString())) {
                    Toast.makeText(getActivity(), "评论内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(workId)) {
                    Toast.makeText(getActivity(), "数据出错", Toast.LENGTH_SHORT).show();
                    return;
                }
                contentMsg = et.getText().toString();
                for (AttentFansbean.Data d : atList) {
                    String s = "<nickName@" + d.nickName + "&profileId@" + d.profileId + "%cosfun>";
                    String o = "@" + d.nickName;
                    if (contentMsg.indexOf(s) < 0) {//如果已经替换则跳过
                        contentMsg = contentMsg.replace(o, s);
                    }

                }
                LogUtils.e("testcomm", "contentMsg=" + contentMsg);
                if (StringUtils.isFastDoubleClick(500)){
                    return;
                }
                send.setClickable(false);
                commPresenter.getOpusComm(isTop,workId, "1", "", commId, "", contentMsg);
                break;
            case R.id.bottom_input_dialog_at:
                AtFragment atFragment = AtFragment.newInstance();
                atFragment.setOnItemSelectLisenter(data -> {
                    atList.add(data);
                    String s = et.getText().toString() + "@" + data.nickName;
                    et.setText(s);
                    atFragment.dismiss();
                });
                if (null == getActivity()){
                    return;
                }
                atFragment.show(getActivity().getSupportFragmentManager(), "myFragment");
                break;
        }
    }

    @Override
    public void successStatus(BaseBackBean baseBackBean) {
        send.setClickable(true);
        if (commentDialogListener != null) {
            if (null == baseBackBean.getData()) {
                if (50072 == baseBackBean.getStatus()) {
                    confirmDialog();
                } else if (50073 == baseBackBean.getStatus()) {
                    confirmBlackDialog();
                }
                return;
            }
            commentDialogListener.commSuccess(position, baseBackBean.getData().getCommentUserId(), contentMsg);
        }
        this.dismiss();
    }

    /**
     * 确认弹窗
     */
    private void confirmDialog() {
        @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
        String content = Objects.requireNonNull(getActivity()).getResources().getString(R.string.comment_black, mNickname);
        DialogUtil.getContentDialog(getActivity(), content);
    }

    /**
     * 拉黑别人
     */
    private void confirmBlackDialog() {
        @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
        String content = getResources().getString(R.string.comment_handle, mNickname);
        DialogUtil.getContentCommentDialog(getActivity(), content, mProfileId, dialogListener);
    }


    @Override
    public void succeed(CommBean commBean) {

    }

    @Override
    public void failure(int code, String error) {
      send.setClickable(true);
    }

    @Override
    public void showCancelPullBlack(int data) {

    }

    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }

    public void setAttentData(long attentData, String nickname) {
        this.mProfileId = attentData;
        this.mNickname = nickname;
    }

    public interface CommentDialogListener {
        void commSuccess(int position, String commId, String commStr);
    }

}
